//app.js
var flag_id_pro = "90e6b6b385f394938a13ac58335af73d"; //小程序获取流量主标识->正式服
let servers = require('./utils/server.config.js');

App({

    data: {
        wx_version: '', //微信版本号
        sdk_version: "", //小程序基础库
        app_version: "1.0.1", //小程序版本号
        system: "", //系统版本
        project: '',
        flag_id: flag_id_pro, //小程序获取流量主标识
        identity_type: 1, //账号类别：1-小程序
        systemInfo: {}, //系统信息
        defaultImg: "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83epHNkyMkOeLa9Jzic5Fjt7hpBd6ribppqV1DYUF56E0M4y8qGkADcthOszDNZzMICJHyibkgYeibd8CKw/132",
        userInfo: {},
        loginInfo: {}, //登录信息
        authorizeUserInfo: false,
        formId: "",
        cutMusic: false,
        musicLine: false,
        innerAudioContext: wx.createInnerAudioContext(),
        mp4Url_one: "",
        bannerData: '', //全局广告
        voiceData: "",
    },

    /**
     * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
     */
    onLaunch: function () {
        let that = this;
        console.log(' 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）')
        that.appInitData(() => {
            // that.checkServerLogin(() => { });
        });
        this.data.innerAudioContext.src = this.data.mp4Url_one;
        this.data.innerAudioContext.volume = 0.3;
        this.data.innerAudioContext.autoplay = false;
        this.data.innerAudioContext.startTime = 0;
        this.data.innerAudioContext.loop = true;
        this.data.innerAudioContext.obeyMuteSwitch = false;
        this.data.innerAudioContext.onPause(() => {
            console.log('音频被被暂停')
        })
        this.data.innerAudioContext.onCanplay(() => {
            if (!this.data.cutMusic) {
                this.data.innerAudioContext.play(); //接着上次播放音频
                this.data.innerAudioContext.onPlay(() => {
                    this.data.innerAudioContext.onEnded(() => {
                        console.log('自然播放结束')
                    })
                })
            }
        })
        wx.updateShareMenu({
            withShareTicket: false,
        })
    },

    /**
     * 小程序初始化数据
     */
    appInitData(callback) {
        let that = this;
        that.data.userInfo = wx.getStorageSync('userInfo');
        that.data.loginInfo = wx.getStorageSync('loginInfo');
        console.log('全局取用户信息')
        console.log(that.data.userInfo)
        console.log(that.data.loginInfo)
        if (that.data.userInfo && that.data.loginInfo) {
            that.data.authorizeUserInfo = true;
            callback(true);
        } else {
            that.data.authorizeUserInfo = false;
            wx.removeStorageSync('loginInfo');
            wx.removeStorageSync('userInfo');
            callback(false);
        }
        wx.getSystemInfo({
            success: function (res) {
                console.log('全局设备信息')
                console.log(res)
                that.data.systemInfo = res;
                that.data.sdk_version = res.SDKVersion;
                that.data.wx_version = res.version;
                that.data.system = res.system;
            },
        })
    },

    /**
     * 关闭背景音乐
     */
    stopPlayBackgroundMusic() {
        if (this.data.cutMusic) {
            this.data.innerAudioContext.pause();
        }
    },

    /**
     * 播放背景音乐
     */
    startPlayBackgroundMusic() {
        console.log('播放音乐')
        console.log(this.data.cutMusic)
        if (!this.data.cutMusic) {
            this.data.innerAudioContext.play(); //接着上次播放音频
        }
    },

    /**
     * 当小程序启动，或从后台进入前台显示，会触发 onShow
     */
    onShow: function (options) {
        console.log('当小程序启动，或从后台进入前台显示，会触发 onShow')
        if (this.data.musicLine) {
            this.data.cutMusic = true;
        } else {
            this.data.cutMusic = false;
        }
        this.startPlayBackgroundMusic();
    },

    /**
     * 校验服务token过期
     * @param {Function} callback 回调
     * 回调参数
     * a:本地token未过期，直接登录
     * b:本地token已过期，但未过可刷新时间，刷新token
     * c:本地token已过期，超过了可刷新时间，请重新登录
     * d:无本地token，首次登录
     */
    checkServerLogin(callback) {
        var cTime = new Date();
        var loginInfo = wx.getStorageSync("loginInfo");
        if (loginInfo) {
            if (Date.parse(loginInfo.expired_at.replace(/-/g, "/")) > Date.parse(cTime)) {
                console.log("本地token未过期，直接登录");
                callback();
            } else if (Date.parse(loginInfo.refresh_expired_at.replace(/-/g, "/")) > Date.parse(cTime)) {
                console.log("本地token已过期，但未过可刷新时间，刷新token");
                // wx.removeStorageSync('loginInfo');
                // wx.removeStorageSync('userInfo');
                // if (this.data.userInfo) {
                //     this.wxLogin(callback, () => {});
                // }
                this.refreshServerToken(callback);
            } else {
                console.log("本地token已过期，超过了可刷新时间，请重新登录");
                this.refreshServerToken(callback);
            }
        } else {
            console.log("无本地token，首次登录");
            this.data.authorizeUserInfo = false;
            if (this.data.userInfo) {
                this.wxLogin(callback, () => { });
            } else {
                callback();
            }
        }
    },

    /**
     * 小程序登录
     */
    wxLogin: function (callbackA, callback) {
        let that = this;
        wx.login({
            success: function (res) {
                console.log(res)
                that.data['code'] = res.code;
                console.log('wx.login登陆成功')
                wx.request({
                    url: servers.url_user_login,
                    data: {
                        code: res.code
                    },
                    header: {
                        'content-type': 'application/x-www-form-urlencoded',
                        Accept: that.data.app_version
                    },
                    method: 'POST',
                    success(res) {
                        console.log('校验----》登录成功返回')
                        console.log(res)
                        if (res.statusCode == 201) {
                            let datas = res.data.data.authorization.data;
                            that.data.loginInfo = datas;
                            wx.setStorageSync('loginInfo', datas);
                            console.log(datas)
                        }
                    },
                    fail(res) { },
                    complete() {
                        callback(res.code);
                        callbackA();
                    }
                })
            },
            fail: function (res) {
                console.log('wx.login登陆失败')
                console.log(res)
            }
        })
    },

    refreshServerToken(callback) {
        let that = this;
        wx.request({
            url: servers.url_token_refresh,
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                Authorization: that.data.loginInfo.token ? 'Bearer ' + that.data.loginInfo.token : 'Bearer ' + wx.getStorageSync('loginInfo').token,
                Accept: that.data.app_version
            },
            method: 'POST',
            success(res) {
                console.log('刷新token返回')
                console.log(res)
                var datas = res.data.data.authorization.data;
                that.data.loginInfo = datas;
                wx.setStorageSync('loginInfo', datas);
            },
            fail(res) {
                console.log('刷新tokenfail返回')
                console.log(res)
            },
            complete() {
                callback();
            }
        })
    },

    /**
     * 当小程序从前台进入后台，会触发 onHide
     */
    onHide: function () {
        console.log('当小程序从前台进入后台，会触发 onHide')
        this.data.cutMusic = true;
        this.stopPlayBackgroundMusic();
    },

    /**
     * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
     */
    onError: function (msg) {

    }
})